<template>
  <div class="app-container">
    <el-form :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      class="form-search"
      label-width="100px">
      <el-form-item :label="$t('rateMgt.payoutName')"
        prop="exchangeName">
        <el-input v-model="queryParams.exchangeName"
          :placeholder="$t('common.placeholderContent')"
          clearable
          style="width: 240px"
          maxlength="50"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item :label="$t('rateMgt.isGlobal')"
        prop="isGlobal">
        <el-select v-model="queryParams.isGlobal"
          :placeholder="$t('common.placeholderSelect')"
          clearable
          style="width: 240px">
          <el-option v-for="dict in dict.type.is_global"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('rateMgt.status')"
        prop="status">
        <el-select v-model="queryParams.status"
          :placeholder="$t('common.placeholderSelect')"
          clearable
          style="width: 240px">
          <el-option v-for="dict in dict.type.sys_data_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery">{{$t('common.search')}}</el-button>
        <el-button icon="el-icon-refresh"
          size="mini"
          @click="resetQuery">{{$t('common.reset')}}</el-button>
      </el-form-item>
    </el-form>

    <div class="section-box">
      <el-row :gutter="10"
        class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd">{{$t('common.add')}}</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate">{{$t('common.edit')}}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete">{{$t('common.delete')}}</el-button>
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch"
          @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading"
        :data="rateList">
        <!-- <el-table-column type="selection"
          width="55"
          align="center" /> -->
        <el-table-column :label="$t('rateMgt.payoutName')"
          align="center"
          prop="exchangeName"
          :show-overflow-tooltip="true"
          min-width="150" />
        <el-table-column :label="$t('rateMgt.rate')"
          align="center"
          prop="rate"
          min-width="100" />
        <el-table-column :label="$t('rateMgt.dateRange')"
          align="center"
          prop="rate"
          min-width="200">
          <template slot-scope="scope">
            {{scope.row.startDate}} To {{scope.row.endDate}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('rateMgt.timeRange')"
          align="center"
          prop="rate"
          min-width="160">
          <template slot-scope="scope">
            {{scope.row.startTime}} To {{scope.row.endTime}}
          </template>
        </el-table-column>
        <el-table-column :label="$t('rateMgt.status')"
          align="center"
          min-width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rateMgt.isGlobal')"
          align="isGlobal"
          min-width="120">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.is_global"
              :value="scope.row.isGlobal" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.createBy')"
          align="center"
          prop="createBy"
          min-width="140"
          show-overflow-tooltip />
        <el-table-column :label="$t('common.createTime')"
          align="center"
          prop="createTime"
          min-width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.updateBy')"
          align="center"
          prop="updateBy"
          min-width="140"
          show-overflow-tooltip />
        <el-table-column :label="$t('common.updateTime')"
          align="center"
          prop="updateTime"
          min-width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.remark')"
          prop="remark"
          min-width="160"
          show-overflow-tooltip />
        <el-table-column :label="$t('common.controls')"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          min-width="170">
          <template slot-scope="scope">
            <el-button size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)">{{$t('common.edit')}}</el-button>
            <el-button size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)">{{$t('common.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body>
      <el-form ref="form"
        :model="form"
        :rules="rules"
        label-width="150px">
        <el-form-item :label="$t('rateMgt.isGlobal')">
          <el-radio-group v-model="form.isGlobal">
            <el-radio v-for="dict in dict.type.is_global"
              :key="dict.value"
              :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isGlobal == '0'"
          :label="$t('rateMgt.payoutName')"
          prop="exchangeId">
          <el-select v-model="form.exchangeId"
            filterable
            remote
            reserve-keyword
            :placeholder="$t('common.placeholderSelect')"
            :remote-method="remoteMethod"
            :loading="exhloading"
            style="width: 100%">
            <el-option v-for="item in exchangeList"
              :key="item.exchangeId"
              :label="item.exchangeName"
              :value="item.exchangeId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('rateMgt.rate')"
          prop="rate">
          <div style="display: flex; align-items: center">
            <span style="color: #606266;font-size: 14px"
              class="mr10">1U =</span>
            <el-input v-model="form.rate"
              style="flex: 1;"
              @input="form.rate = onInput(form.rate)"
              :placeholder="$t('common.placeholderContent')">
              <template slot="append">{{$t('common.unit')}}</template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item :label="$t('rateMgt.dateRange')"
          prop="startDate">
          <el-date-picker v-model="dateRange"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('rateMgt.timeRange')"
          prop="startTime">
          <el-time-picker v-model="timeRange"
            is-range
            style="width: 100%"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            range-separator="-"
            :start-placeholder="$t('common.startTime')"
            :end-placeholder="$t('common.endTime')">
          </el-time-picker>
        </el-form-item>
        <el-form-item :label="$t('rateMgt.status')">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_data_status"
              :key="dict.value"
              :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('common.remark')">
          <el-input v-model="form.remark"
            type="textarea"
            maxlength="200"
            :placeholder="$t('common.placeholderContent')"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button type="primary"
          @click="submitForm">{{$t('common.ok')}}</el-button>
        <el-button @click="cancel">{{$t('common.cancel')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getRateList,
  rateDetail,
  addRate,
  updateRate,
  delRate,
  changeRateStatus,
} from "@/api/exchangeRate/index.js";
import {
  getExhUserList,
} from "@/api/system/exchangeUser.js";
import { onInput } from '@/utils/util.js'

export default {
  name: "rate",
  dicts: ["sys_data_status", "is_global"],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      rateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 时间范围
      timeRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        exchangeName: undefined,
        isGlobal: undefined,
        status: undefined,
        recordType: 'payout'
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        exchangeId: [
          { required: true, message: this.$t('common.ruleSelectEmpty'), trigger: "change" },
        ],
        rate: [
          { required: true, message: this.$t('common.ruleInputEmpty'), trigger: "blur" },
        ],
        startDate: [
          { required: true, message: this.$t('common.ruleSelectEmpty'), trigger: "change" },
        ],
        startTime: [
          { required: true, message: this.$t('common.ruleSelectEmpty'), trigger: "change" },
        ]
      },
      exhloading: false,
      exchangeList: []
    };
  },
  watch: {
    dateRange (val) {
      if (val) {
        this.form.startDate = val[0]
        this.form.endDate = val[1]
      } else {
        this.form.startDate = null
        this.form.endDate = null
      }
    },
    timeRange (val) {
      if (val) {
        this.form.startTime = val[0]
        this.form.endTime = val[1]
      } else {
        this.form.startTime = null
        this.form.endTime = null
      }
    },
    ['form.isGlobal'] (val) {
      if (val == '1') {
        this.form.exchangeId = null
        this.form.exchangeName = null
      }
    }
  },
  created () {
    this.getList();
  },
  methods: {
    onInput,
    // 搜索汇兑用户
    remoteMethod (query) {
      if (query !== '') {
        this.exhloading = true;
        getExhUserList({
          pageNum: 1,
          pageSize: 10,
          exchangeName: query,
          status: 1,
          payType: 'payout'
        }).then(
          (response) => {
            this.exchangeList = response.rows;
            this.exhloading = false;
          }
        );
      } else {
        this.exchangeList = [];
      }
    },
    /** 查询汇率列表 */
    getList () {
      this.loading = true;
      getRateList(this.queryParams).then(
        (response) => {
          this.rateList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 汇率状态修改
    handleStatusChange (row) {
      // let text = row.status === "0" ? "启用" : "停用";
      let text = '';
      let tips = ''
      if (row.status === "1") {
        text = `${this.$t('common.statusChangesEnable')} ${row.exchangeName} ?`
        tips = this.$t('common.enabledSuccessfully')
      } else {
        text = `${this.$t('common.statusChangesDisable')} ${row.exchangeName} ?`
        tips = this.$t('common.disableSuccessfully')
      }
      this.$modal
        // .confirm('确认要"' + text + '""' + row.roleName + '"吗？')
        .confirm(text)
        .then(function () {
          return changeRateStatus({
            status: row.status,
            rateId: row.rateId
          });
        })
        .then(() => {
          this.$modal.msgSuccess(tips);
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        exchangeId: null,
        isGlobal: '1',
        startDate: null,
        endDate: null,
        startTime: '08:00:00',
        endTime: '18:00:00',
        rate: null,
        status: '1',
        remark: null,
        recordType: 'payout'
      };
      this.dateRange = []
      this.timeRange = ['08:00:00', '18:00:00']
      this.exchangeList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.rateId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = this.$t('rateMgt.addRate');
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const rateId = row.rateId || this.ids;
      rateDetail(rateId).then((response) => {
        this.form = response.data;
        this.exchangeList = [{
          exchangeId: this.form.exchangeId,
          exchangeName: this.form.exchangeName,
        }]
        this.dateRange = [this.form.startDate, this.form.endDate]
        this.timeRange = [this.form.startTime, this.form.endTime]
        this.open = true;
        this.title = this.$t('rateMgt.editRate');
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.rateId != undefined) {
            updateRate(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('common.editSuccessfully'));
              this.open = false;
              this.getList();
            });
          } else {
            addRate(this.form).then((response) => {
              this.$modal.msgSuccess(this.$t('common.newSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const rateIds = row.rateId || this.ids;
      this.$modal
        // .confirm('是否确认删除Rate id编号为"' + rateIds + '"的数据项？')
        .confirm(this.$t('common.deleteDataTips'))
        .then(function () {
          return delRate(rateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('common.successfullyDeleted'));
        })
        .catch(() => { });
    }
  },
};
</script>
